#!/usr/bin/env python
#==============================================================================
#
#  $Id$
#
"""
    Performance tester.
"""
#
#   Copyright (C) 2003 Michael A. Muller
#
#   This file is part of ODB.
#
#   ODB is free software: you can redistribute it and/or modify it under the 
#   terms of the GNU Lesser General Public License as published by the Free 
#   Software Foundation, either version 3 of the License, or (at your option) 
#   any later version.
#
#   ODB is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License 
#   along with ODB.  If not, see <http://www.gnu.org/licenses/>.
#
#==============================================================================


import random, time, os, shutil
import fixpath
from odb import Env
from utils import SortedList

def insertRandomKey(db, backup):
    """
        Parms:
            db::
                an ODB database
            backup::
                [SortedList] the contents of the database in list form.
    """
    
    # pick a unique random key
    key = `random.random()`
    while db.has_key(key):
       key = `random.random()`
    
    # assign it to a value
    val = random.random()
    db[key] = val
    backup.add(key, val)

if os.path.exists('odb_test_db'): shutil.rmtree('odb_test_db')

try:
    env = Env('odb_test_db')
    db = env.getBTreeDB('Table')

    backup = SortedList()
    
    count = 1000

    # time random actions
    t = time.time()
    for i in xrange(count):
        action = random.randrange(0, 2)
            
        if action == 0 and backup:
            # delete a random key
            key, val = random.choice(backup)
            del db[key]
            backup.remove(key)

        else:
            insertRandomKey(db, backup)
    
    print 'time for %d actions: %g secs' % (count, time.time() - t)

    # do 1000 insertions
    t = time.time()
    for i in xrange(count):
        insertRandomKey(db, backup)
    print 'time for %d insertions: %g secs' % (count, time.time() - t)
    
    # do checkpointing
    t = time.time()
    env.checkpoint()
    print 'time to checkpoint %d insertions: %g secs' % \
          (len(backup), time.time() - t)
        
finally:
    os.system('ls -l odb_test_db')
    if os.path.exists('odb_test_db'): shutil.rmtree('odb_test_db')

